package com.coco.service.impl;

import com.coco.config.RedisService;
import com.coco.exception.MyException;
import com.coco.result.RemotePhoneDetail;
import com.coco.result.Result;
import com.coco.service.PhoneService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.io.IOException;
import java.time.Duration;

@Service
public class PhoneServiceImpl implements PhoneService {
    @Autowired
    private RedisService redisService;

    @Override
    public Result<RemotePhoneDetail> searchLocation(String phone) {
        Result<RemotePhoneDetail> result = null;
        //todo 添加缓存机制 从token中查
        String key = "phone:" + phone;
        String phoneDetail = redisService.get(key);
        //判断redis中是否存在该手机号
        if (ObjectUtils.isEmpty(phoneDetail)) {
            //接口调用
            Result<RemotePhoneDetail> apiResult = remoteApi(phone);
            try {
                ObjectMapper mapper = new ObjectMapper();
                //json字符串
                String value = mapper.writeValueAsString(apiResult);
                //设置进redis中
                //随机过期时间
                Duration time = Duration.ofMinutes(2).plus(Duration.ofSeconds((int) Math.random() * 100));
                //存入redis
                redisService.set(key, value, time);
                return apiResult;
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }
        //存在从redis取
        ObjectMapper mapper = new ObjectMapper();
        try {
            //解析json字符串
            result = mapper.readValue(phoneDetail,
                    new TypeReference<Result<RemotePhoneDetail>>() {
                    });
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return result;
    }

    /**
     * 远程接口
     *
     * @param phone
     * @return
     */
    private Result<RemotePhoneDetail> remoteApi(String phone) {
        String url = "http://v2.xxapi.cn/api/phoneAddress?phone=" + phone;
        Result<RemotePhoneDetail> result = null;
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet request = new HttpGet(url);
            CloseableHttpResponse response = httpClient.execute(request);
            int status = response.getCode();
            if (status == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                String jsonStr = EntityUtils.toString(entity);
                ObjectMapper mapper = new ObjectMapper();
                result = mapper.readValue(jsonStr,
                        new TypeReference<Result<RemotePhoneDetail>>() {
                        });
                return result;
            } else {
                return Result.error("查询失败");
            }
        } catch (Exception e) {
            throw new MyException("运营商不存在");
        }
    }
}
